package com.hsnn.medstgmini.base.dict.dao.impl;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.hsnn.medstgmini.base.dict.dao.DicDrugspecLogDao;
import com.hsnn.medstgmini.base.dict.model.DicDrugspecLog;
import com.hsnn.medstgmini.util.Pagination;

/**
 * 基础库 数据字典 规格字典 维护记录接口实现类
 * 
 * @author hssdzxssh
 *
 */
@Repository
public class DicDrugspecLogDaoImpl extends BaseHibernateDAO implements
		DicDrugspecLogDao {
	
	@Resource(name = "sessionFactory")
	private SessionFactory sessionFactory;
	
	
	/**
	 * 基础库 数据字典 规格字典 维护记录添加
	 * 
	 * @param dicDrugspecLog
	 */
	@Override
	public boolean add(DicDrugspecLog dicDrugspecLog) {
			getSession().clear();
			this.getSession().saveOrUpdate(dicDrugspecLog);
			getSession().flush();
			return true;
	}

	/**
	 * 基础库 数据字典 规格字典 维护记录查询所有及条件查询
	 * 
	 * @param dicDrugspecLog
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@Override
	public List<DicDrugspecLog> queryDicDrugspecLogByName(Pagination page,
			DicDrugspecLog dicDrugspecLog) {
		String specId = dicDrugspecLog.getSpecId();
		String date1 = dicDrugspecLog.getSpecCode();
		String date2 = dicDrugspecLog.getSpecName();
		StringBuffer hql = new StringBuffer();
		StringBuffer hqlCount = new StringBuffer();
		hqlCount.append(" select count(*) from DicDrugspecLog where spec_id = ? ");
		hql.append(" from DicDrugspecLog where spec_id = ? ");
		if (null != date1 && !("").equals(date1)) {
			hqlCount.append(" and upd_datetime > ?");
			hql.append(" and upd_datetime > ?");
		} else if (null != date1 && !("").equals(date1)) {
			hqlCount.append(" and upd_datetime < ? ");
			hql.append(" and upd_datetime < ? ");
		} else if (null != date1 && !("").equals(date1)
				&& (null != date2 && !("").equals(date2))) {
			hqlCount.append(" and (upd_datetime between  ? and  ? )");
			hql.append(" and (upd_datetime between  ? and  ? )");
		}
		hql.append(" order by upd_datetime ");
		Query query = getSession().createQuery(hql.toString());
		Query queryCount = getSession().createQuery(hqlCount.toString());
		query.setParameter(0, specId);
		queryCount.setParameter(0, specId);
		if (null != date1 && !("").equals(date1)) {
			query.setParameter(1, date1);
			queryCount.setParameter(1, date1);
		} else if (null != date2 && !("").equals(date2)) {
			query.setParameter(1, date2);
			queryCount.setParameter(1, date2);
		} else if (null != date1 && !("").equals(date1)
				&& (null != date2 && !("").equals(date2))) {
			query.setParameter(1, date1);
			query.setParameter(2, date2);
			queryCount.setParameter(1, date1);
			queryCount.setParameter(2, date2);
		}
		dicDrugspecLog.setCount(Long.valueOf(queryCount.list().get(0)+""));
		query.setFirstResult((page.getPage()-1)*page.getMaxResults());
		query.setMaxResults(page.getMaxResults());
		return query.list();
		
	}

	@Override
	public Pagination queryDicDrugspecLogList(Pagination page) {
		String date1 = page.getConditions().get("date1");
		String date2 = page.getConditions().get("date2");
		String specId = page.getConditions().get("specId");
		String specCode =page.getConditions().get("specCode");
		StringBuffer sql1 = new StringBuffer();
		sql1.append("	    SELECT a.spec_code father_spec_code,a.spec_name father_spec_name,NULL m,NULL n,a.status,    ")
			.append("		s.name,a.upd_datetime,a.log_id logId,a.detail detail FROM  dic_drugspec_log a     ")
			.append("	     LEFT JOIN sys_user s ON s.id=a.upd_user               ")
			.append("       WHERE a.spec_id=:specId                                ");
		StringBuffer sql2 = new StringBuffer();
		sql2.append("SELECT a.spec_code father_spec_code,a.spec_name father_spec_name,b.spec_code,b.spec_name,       ")
		    .append(" b.status,s.name,b.upd_datetime,b.log_id logId,b.detail detail FROM  dic_drugspec_log b  ")
		    .append(" INNER JOIN dic_drugspec a ON a.spec_id=b.father_id           ")
		    .append(" LEFT JOIN sys_user s ON s.id=b.upd_user                      ")
		    .append(" WHERE b.spec_id=:specId                                      ");
		StringBuffer sqlCount1 = new StringBuffer();
		sqlCount1.append("SELECT COUNT(*) FROM dic_drugspec_log a ")
		         .append(" WHERE spec_id=:specId ");
		StringBuffer sqlCount2 = new StringBuffer();
		sqlCount2.append("SELECT COUNT(*) FROM dic_drugspec_log b   ")
		         .append(" INNER JOIN dic_drugspec a ON a.spec_id=b.father_id  ")
		         .append(" WHERE b.spec_id=:specId ");
		if(StringUtils.isNotBlank(specCode)){
			if(StringUtils.isNotBlank(date1)){
				sql2.append(" and b.upd_datetime >= :date1 ");
				sqlCount2.append(" and b.upd_datetime >= :date1 ");
			}
			if(StringUtils.isNotBlank(date2)){
				sql2.append(" and b.upd_datetime <= :date2 ");
				sqlCount2.append(" and b.upd_datetime <= :date2 ");
			}
			sql2.append(" order by b.upd_datetime desc");
			Query query = getSession().createSQLQuery(sql2.toString());
			Query queryCount = getSession().createSQLQuery(sqlCount2.toString());
			query.setString("specId", specId);
			queryCount.setString("specId", specId);
			if(StringUtils.isNotBlank(date1)){
				query.setString("date1", date1+" 00:00:00");
				queryCount.setString("date1", date1+" 00:00:00");
			}
			if(StringUtils.isNotBlank(date2)){
				query.setString("date2", date2+" 23:59:59");
				queryCount.setString("date2", date2+" 23:59:59");
			}
			page.setRecords(Long.parseLong(queryCount.uniqueResult().toString()));
			query.setFirstResult((page.getPage()-1)*page.getMaxResults());
			query.setMaxResults(page.getMaxResults());
			page.setRows(query.list());
			return page;
		}else{
			if(StringUtils.isNotBlank(date1)){
				sql1.append(" and a.upd_datetime >= :date1 ");
				sqlCount1.append(" and a.upd_datetime >= :date1 ");
			}
			if(StringUtils.isNotBlank(date2)){
				sql1.append(" and a.upd_datetime <= :date2 ");
				sqlCount1.append(" and a.upd_datetime <= :date2 ");
			}
			sql1.append(" order by a.upd_datetime desc");
			Query query = getSession().createSQLQuery(sql1.toString());
			Query queryCount = getSession().createSQLQuery(sqlCount1.toString());
			query.setString("specId", specId);
			queryCount.setString("specId", specId);
			if(StringUtils.isNotBlank(date1)){
				query.setString("date1", date1+" 00:00:00");
				queryCount.setString("date1", date1+" 00:00:00");
			}
			if(StringUtils.isNotBlank(date2)){
				query.setString("date2", date2+" 23:59:59");
				queryCount.setString("date2", date2+" 23:59:59");
			}
			page.setRecords(Long.parseLong(queryCount.uniqueResult().toString()));
			query.setFirstResult((page.getPage()-1)*page.getMaxResults());
			query.setMaxResults(page.getMaxResults());
			page.setRows(query.list());
			return page;
		}
		
	
	}

	
	/**
	 * 基础库 数据字典 剂型字典 根据id查询 规格 日志详情
	 * @param result
	 * @param dicDrugspecLog
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@Override
	public List<Map<String, Object>> getDrugSpecHisDetail(Pagination page) {
		Session session = sessionFactory.getCurrentSession();
		String logId = page.getConditions().get("logId");
		StringBuffer  sql = new StringBuffer();
		sql.append(" SELECT case when b.father_id = '0' then b.spec_code else a.spec_code end fatherSpecCode,  ")
		   .append(" case when b.father_id = '0' then b.spec_name else a.spec_name end fatherSpecName, ")
		   .append(" case when b.father_id = '0' then null else b.spec_code end specCode,")
		   .append(" case when b.father_id = '0' then null else b.spec_name end specName,b.status status,b.log_id logId , ")
		   .append(" date_format(b.upd_datetime,'%Y-%m-%d %T') updDatetime,s.name updUser FROM  dic_drugspec_log b  ")
		   .append(" LEFT JOIN dic_drugspec a ON a.spec_id=b.father_id  LEFT JOIN sys_user s ON s.id=b.upd_user  ")
		   .append(" WHERE b.spec_id = (SELECT spec_id FROM dic_drugspec_log WHERE log_id = :logId )  ")
		   .append(" AND b.upd_datetime <= (SELECT upd_datetime FROM dic_drugspec_log where log_id = :logId ) ")
		   .append(" order by b.upd_datetime desc limit 2");
		Query query = session.createSQLQuery(sql.toString());
		query.setString("logId", logId);
		query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
		return query.list();
	}
	
	
}
